#include "BRDFPhoto.h"
#include <fstream>
using namespace std;


CBRDFPhoto::CBRDFPhoto(char* filename, CCamera* pCamera)
	: CPhoto(pCamera)
{
	int i = 0;
	while (filename[i])
	{
		m_fileName[i] = filename[i];
		i++;
	}
	m_fileName[i] = '\0';
	m_objectPoints.clear();
	m_imagePoints.clear();
	if (LoadFeaturesFromFile())
		ComputeExtrinsicParas();
}

CBRDFPhoto::CBRDFPhoto(const CBRDFPhoto& photo)
	: CPhoto(photo)
{
	int i = 0;
	while (photo.m_fileName[i])
	{
		m_fileName[i] = photo.m_fileName[i];
		i++;
	}
	m_fileName[i] = '\0';
	int n = photo.m_objectPoints.size();
	m_objectPoints.clear();
	m_imagePoints.clear();
	for (int i = 0; i < n; i++)
	{
		m_objectPoints.push_back(photo.m_objectPoints[i]);
		m_imagePoints.push_back(photo.m_imagePoints[i]);
	}
}

void CBRDFPhoto::AddPoints(float opx, float opy, float opz, float ipx, float ipy)
{
	CPoint3D op;
	op.m_x = opx;
	op.m_y = opy;
	op.m_z = opz;
	CPixel ip;
	ip.m_x = ipx;
	ip.m_y = ipy;
	m_objectPoints.push_back(op);
	m_imagePoints.push_back(ip);
}

void CBRDFPhoto::ComputeExtrinsicParas()
{
	CalcExtrinsicParas(m_imagePoints, m_objectPoints);
}

void CBRDFPhoto::SaveFeaturesIntoFile()
{
	ofstream fout(m_fileName);
	int length = m_imagePoints.size();
	fout << length << endl;
	for (int i = 0; i < length; i++)
	{
		fout << m_imagePoints[i].m_x << ' ' << m_imagePoints[i].m_y << ' '
			<< m_objectPoints[i].m_x << ' ' << m_objectPoints[i].m_y << ' '
			<< m_objectPoints[i].m_z << endl;
	}
	fout.close();
}

bool CBRDFPhoto::LoadFeaturesFromFile()
{
	ifstream fin(m_fileName);
	if (!fin.is_open())
		return false;
	m_imagePoints.clear();
	m_objectPoints.clear();
	int length;
	fin >> length;
	CPixel pixel;
	CPoint3D point;
	for (int i = 0; i < length; i++)
	{
		fin >> pixel.m_x >> pixel.m_y >> point.m_x >> point.m_y >> point.m_z;
		m_imagePoints.push_back(pixel);
		m_objectPoints.push_back(point);
	}
	fin.close();
	return true;
}